<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useQuasar } from 'quasar';
import PracticeDetail from './PracticeDetail.vue';

const props = defineProps<{
  problems: Array<{
    expression: string;
    answer: number;
    displayExpression: string;
  }>;
}>();

const emit = defineEmits(['close']);

const $q = useQuasar();

// 当前题目索引
const currentIndex = ref(0);
// 用户输入的答案
const userAnswer = ref('');
// 用户答案记录
const userAnswers = ref<Array<{
  answer: string;
  isCorrect: boolean;
  timeSpent: number; // 每道题花费的时间（秒）
  startTime: number; // 开始时间戳
}>>([]);
// 是否显示结果
const showResult = ref(false);
// 是否显示详细答题记录
const showDetailedResults = ref(false);
// 是否可以关闭结果
const canCloseResult = ref(false);
// 结果倒计时
const resultCountdown = ref(3);
// 开始时间
const startTime = ref(0);
// 计时器
const timer = ref(0);
// 计时器间隔
let timerInterval: number | null = null;

// 添加耗时分析相关的状态
const showTimeAnalysis = ref(false);
const sortByTime = ref(false);
const highlightLongTime = ref(true);
const longTimeThreshold = ref(6); // 默认6秒

// 添加暂存答题状态
const savedProgress = ref<{
  currentIndex: number;
  userAnswers: Array<{
    answer: string;
    isCorrect: boolean;
    timeSpent: number;
    startTime: number;
  }>;
  startTime: number;
  timestamp: number; // 添加时间戳用于判断是否过期
} | null>(null);

// 检查是否有暂存的答题进度
const hasSavedProgress = computed(() => {
  return savedProgress.value !== null;
});

// 当前题目
const currentProblem = computed(() => props.problems[currentIndex.value]);

// 计算总用时（秒）
const totalTime = computed(() => {
  return (Date.now() - startTime.value) / 1000;
});

// 格式化时间显示
const formatTime = (seconds: number) => {
  return `${seconds.toFixed(1)}秒`;
};

// 计算得分
const score = computed(() => {
  return userAnswers.value.filter(answer => answer.isCorrect).length;
});

// 计算正确率
const accuracy = computed(() => {
  if (userAnswers.value.length === 0) return 0;
  return Math.round((score.value / userAnswers.value.length) * 100);
});

// 获取错题列表
const wrongProblems = computed(() => {
  return userAnswers.value
    .map((answer, index) => ({
      problem: props.problems[index],
      userAnswer: answer.answer,
      timeSpent: answer.timeSpent
    }))
    .filter((_, index) => !userAnswers.value[index].isCorrect);
});

// 计算平均耗时
const averageTime = computed(() => {
  if (userAnswers.value.length === 0) return 0;
  const total = userAnswers.value.reduce((sum, answer) => sum + answer.timeSpent, 0);
  return total / userAnswers.value.length;
});

// 计算最长耗时
const maxTime = computed(() => {
  if (userAnswers.value.length === 0) return 0;
  return Math.max(...userAnswers.value.map(answer => answer.timeSpent));
});

// 按耗时排序的答题记录
const sortedAnswers = computed(() => {
  const answers = userAnswers.value.map((answer, index) => ({
    ...answer,
    problem: props.problems[index],
    index: index + 1
  }));
  
  if (sortByTime.value) {
    return [...answers].sort((a, b) => b.timeSpent - a.timeSpent);
  }
  return answers;
});

// 生成耗时分布数据
const timeDistribution = computed(() => {
  const distribution = new Array(10).fill(0); // 0-1s, 1-2s, ..., 9-10s, >10s
  const maxTime = 10; // 最大显示10秒
  
  userAnswers.value.forEach(answer => {
    const time = Math.min(answer.timeSpent, maxTime);
    const index = Math.floor(time);
    distribution[index]++;
  });
  
  return distribution;
});

// 开始计时
const startTimer = () => {
  startTime.value = Date.now();
  timerInterval = window.setInterval(() => {
    timer.value = (Date.now() - startTime.value) / 1000;
  }, 100);
};

// 停止计时
const stopTimer = () => {
  if (timerInterval) {
    clearInterval(timerInterval);
    timerInterval = null;
  }
};

// 处理数字输入
const handleNumberInput = (num: string) => {
  if (userAnswer.value.length < 5) { // 限制最大输入长度为5位
    userAnswer.value += num;
  }
};

// 处理删除
const handleDelete = () => {
  userAnswer.value = userAnswer.value.slice(0, -1);
};

// 保存练习记录
const savePracticeRecord = async () => {
  try {
    const record = {
      practiceDate: new Date().toISOString(),
      totalProblems: props.problems.length,
      correctCount: score.value,
      accuracy: accuracy.value,
      totalTime: totalTime.value,
      details: userAnswers.value.map((answer, index) => ({
        problem: props.problems[index],
        userAnswer: answer.answer,
        isCorrect: answer.isCorrect,
        timeSpent: answer.timeSpent
      }))
    };

    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/practice/record`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(record)
    });

    const data = await response.json();
    if (!data.success) {
      throw new Error(data.message);
    }
  } catch (error) {
    console.error('保存练习记录失败:', error);
    $q.notify({
      message: '保存练习记录失败',
      color: 'negative'
    });
  }
};

// 修改关闭答题界面的处理函数
const handleClose = () => {
  if (showResult.value) {
    // 如果正在显示结果，需要等待倒计时
    if (!canCloseResult.value) return;
    
    // 如果正在显示详情，直接关闭详情
    if (showDetailedResults.value) {
      showDetailedResults.value = false;
      return;
    }

    // 如果是结果页面，直接关闭
    stopTimer();
    emit('close');
    return;
  }

  // 显示确认对话框
  $q.dialog({
    title: '确认关闭',
    message: '是否要保存当前答题进度并关闭？',
    persistent: true,
    ok: {
      label: '是',
      color: 'primary'
    },
    cancel: {
      label: '否',
      color: 'negative'
    }
  }).onOk(() => {
    // 保存当前进度
    const progress = {
      currentIndex: currentIndex.value,
      userAnswers: [...userAnswers.value],
      startTime: startTime.value,
      timestamp: Date.now()
    };
    savedProgress.value = progress;
    saveProgressToStorage(progress);
    stopTimer();
    emit('close');
  }).onCancel(() => {
    // 用户取消关闭
  });
};

// 添加恢复答题的函数
const restoreProgress = () => {
  if (savedProgress.value) {
    currentIndex.value = savedProgress.value.currentIndex;
    userAnswers.value = [...savedProgress.value.userAnswers];
    startTime.value = savedProgress.value.startTime;
    userAnswer.value = savedProgress.value.userAnswers[savedProgress.value.currentIndex]?.answer || '';
    savedProgress.value = null;
    saveProgressToStorage(null); // 清除存储的进度
    startTimer();
  }
};

// 组件挂载时检查是否有暂存进度
onMounted(() => {
  const storedProgress = loadProgressFromStorage();
  if (storedProgress) {
    savedProgress.value = storedProgress;
    $q.dialog({
      title: '发现暂存进度',
      message: '是否继续上次的答题？',
      persistent: true,
      ok: {
        label: '是',
        color: 'primary'
      },
      cancel: {
        label: '否',
        color: 'negative'
      }
    }).onOk(() => {
      restoreProgress();
    }).onCancel(() => {
      savedProgress.value = null;
      saveProgressToStorage(null);
      startTimer();
    });
  } else {
    startTimer();
  }
});

// 组件卸载时停止计时
onUnmounted(() => {
  stopTimer();
});

// 处理确认
const handleConfirm = () => {
  if (!userAnswer.value) {
    $q.notify({
      message: '请输入答案',
      color: 'warning'
    });
    return;
  }

  const isCorrect = parseInt(userAnswer.value) === currentProblem.value.answer;
  const currentTime = Date.now();
  
  // 计算当前题目的实际用时
  let timeSpent;
  if (currentIndex.value === 0) {
    timeSpent = (currentTime - startTime.value) / 1000;
  } else {
    const previousEndTime = userAnswers.value[currentIndex.value - 1].startTime;
    timeSpent = (currentTime - previousEndTime) / 1000;
  }

  userAnswers.value[currentIndex.value] = {
    answer: userAnswer.value,
    isCorrect,
    timeSpent,
    startTime: currentTime
  };

  // 如果是最后一题，显示结果
  if (currentIndex.value === props.problems.length - 1) {
    stopTimer();
    showResult.value = true;
    // 保存练习记录
    savePracticeRecord();
    // 清除暂存数据
    savedProgress.value = null;
    saveProgressToStorage(null);
    // 开始结果倒计时
    canCloseResult.value = false;
    resultCountdown.value = 3;
    const timer = setInterval(() => {
      resultCountdown.value--;
      if (resultCountdown.value <= 0) {
        clearInterval(timer);
        canCloseResult.value = true;
      }
    }, 1000);
  } else {
    // 切换到下一题
    currentIndex.value++;
    userAnswer.value = '';
  }
};

// 处理上一题
const handlePrevious = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
    userAnswer.value = userAnswers.value[currentIndex.value]?.answer || '';
  }
};

// 重新开始
const handleRestart = () => {
  currentIndex.value = 0;
  userAnswer.value = '';
  userAnswers.value = [];
  showResult.value = false;
  showDetailedResults.value = false;
  startTimer();
};

// 保存进度到 localStorage
const saveProgressToStorage = (progress: typeof savedProgress.value) => {
  if (progress) {
    localStorage.setItem('mathPracticeProgress', JSON.stringify(progress));
  } else {
    localStorage.removeItem('mathPracticeProgress');
  }
};

// 从 localStorage 加载进度
const loadProgressFromStorage = () => {
  const stored = localStorage.getItem('mathPracticeProgress');
  if (stored) {
    const progress = JSON.parse(stored);
    // 检查是否过期（2小时 = 7200000毫秒）
    if (Date.now() - progress.timestamp < 7200000) {
      return progress;
    } else {
      // 如果过期，清除存储
      localStorage.removeItem('mathPracticeProgress');
    }
  }
  return null;
};
</script>

<template>
  <div class="problem-solver">
    <!-- 顶部信息栏 -->
    <div class="row justify-between items-center q-pa-md">
      <div class="text-h6">在线答题</div>
      <div class="text-subtitle2">
        第 {{ currentIndex + 1 }}/{{ problems.length }} 题
        <span class="q-ml-md">用时：{{ formatTime(timer) }}</span>
      </div>
    </div>

    <!-- 答题区域 -->
    <div v-if="!showResult" class="q-pa-md">
      <!-- 题目显示 -->
      <div class="problem-display q-pa-lg text-center">
        <div class="text-h4">{{ currentProblem.displayExpression }}</div>
        <div class="text-h5 q-mt-md">{{ userAnswer || '?' }}</div>
      </div>

      <!-- 虚拟键盘 -->
      <div class="virtual-keyboard q-pa-md">
        <div class="row q-col-gutter-sm">
          <div v-for="n in 9" :key="n" class="col-4">
            <q-btn
              class="full-width"
              :label="n.toString()"
              @click="handleNumberInput(n.toString())"
              color="primary"
              size="lg"
            />
          </div>
          <div class="col-4">
            <q-btn
              class="full-width"
              label="0"
              @click="handleNumberInput('0')"
              color="primary"
              size="lg"
            />
          </div>
          <div class="col-4">
            <q-btn
              class="full-width"
              label="删除"
              @click="handleDelete"
              color="negative"
              size="lg"
            />
          </div>
          <div class="col-4">
            <q-btn
              class="full-width"
              label="确认"
              @click="handleConfirm"
              color="positive"
              size="lg"
            />
          </div>
        </div>
      </div>

      <!-- 导航按钮 -->
      <div class="row justify-between q-mt-md">
        <q-btn
          label="上一题"
          @click="handlePrevious"
          :disable="currentIndex === 0"
          color="secondary"
        />
        <q-btn
          label="关闭"
          @click="handleClose"
          color="negative"
          :disable="showResult && !canCloseResult"
        />
      </div>
    </div>

    <!-- 结果显示 -->
    <div v-else class="q-pa-md">
      <div class="text-h5 text-center q-mb-lg">答题结果</div>
      <div class="text-h6 text-center q-mb-md">
        得分：{{ score }}/{{ problems.length }}
      </div>
      <div class="text-h6 text-center q-mb-lg">
        正确率：{{ accuracy }}%
      </div>

      <PracticeDetail
        v-if="showDetailedResults"
        :details="userAnswers.map((answer, index) => ({
          problem: problems[index],
          userAnswer: answer.answer,
          isCorrect: answer.isCorrect,
          timeSpent: answer.timeSpent
        }))"
        :total-problems="problems.length"
        :total-time="totalTime"
        :accuracy="accuracy"
        :show-header="false"
      />

      <div v-if="!canCloseResult" class="text-caption text-grey text-center q-mt-md">
        请稍候 {{ resultCountdown }} 秒...
      </div>

      <div class="row justify-center q-gutter-md q-mt-lg">
        <q-btn
          :label="showDetailedResults ? '隐藏详情' : '查看详情'"
          @click="showDetailedResults = !showDetailedResults"
          color="secondary"
          :disable="!canCloseResult"
        />
        <q-btn
          label="重新开始"
          @click="handleRestart"
          color="primary"
          :disable="!canCloseResult"
        />
        <q-btn
          label="关闭"
          @click="handleClose"
          color="negative"
          :disable="!canCloseResult"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.problem-solver {
  max-width: 600px;
  margin: 0 auto;
}

.problem-display {
  background: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 20px;
}

.virtual-keyboard {
  background: #f5f5f5;
  border-radius: 8px;
}

@media (max-width: 600px) {
  .problem-solver {
    padding: 0;
  }
  
  .virtual-keyboard {
    padding: 8px;
  }
}

.time-distribution-chart {
  display: flex;
  align-items: flex-end;
  height: 200px;
  gap: 4px;
  margin-bottom: 4px;
  padding-top: 20px;
  border-left: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
}

.chart-bar {
  flex: 1;
  background-color: #1976D2;
  margin: 0 3px;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  min-height: 4px;
  transition: height 0.3s;
}

.chart-labels {
  display: flex;
  justify-content: space-around;
}

.chart-label {
  flex: 1;
  text-align: center;
  font-size: 12px;
  color: #666;
}

.long-time {
  background-color: rgba(255, 0, 0, 0.1);
}
</style> 